package com.szt.mobile.inventory.modules.inventory.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.handset.pakage.UHFTag;
import com.isoftstone.mis.ffair.util.log.FFLog;
import com.szt.mobile.inventory.R;
import com.szt.mobile.inventory.app.HandsetApplication;
import com.szt.mobile.inventory.common.entity.Assets;
import com.szt.mobile.inventory.common.entity.AssetsDao;
import com.szt.mobile.inventory.common.entity.AssetsList;
import com.szt.mobile.inventory.common.entity.Inventory;
import com.szt.mobile.inventory.common.entity.InventoryDao;
import com.szt.mobile.inventory.common.ui.BaseActivity;
import com.szt.mobile.inventory.common.ui.GeneralAdapter;
import com.szt.mobile.inventory.common.utils.DBUtil;
import com.szt.mobile.inventory.common.utils.DialogUtil;
import com.szt.mobile.inventory.common.utils.SpUtil;
import com.szt.mobile.inventory.modules.main.ui.MainActivity;
import com.szt.mobile.inventory.modules.main.ui.PowerSettingActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by yanzhaodi on 2017/11/16.
 */

@SuppressWarnings("unchecked")
public class InventoryListActivity extends BaseActivity {

    @BindView(R.id.lv_inventory_list)
    ListView inventoryListLv;

    private Inventory inventory;
    private AssetsAdapter assetsAdapter;

    private InventoryDao inventoryDao;
    private AssetsDao assetsDao;

    private HandsetApplication application;
    private static volatile boolean bGetEPC;
    private boolean isbGetEPC;
    private List<String> rfidList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_inventory_list);
        ButterKnife.bind(this);
        rfidList = new ArrayList();
        application = ((HandsetApplication) getApplication());

        inventoryDao = DBUtil.getInventoryDao(getApplicationContext());
        assetsDao = DBUtil.getAssetsDao(getApplicationContext());

        inventory = (Inventory) getIntent().getSerializableExtra(InventoryActivity.KEY_INVENTORY);

        List<Assets> assets = new ArrayList<>();
        for (AssetsList assetsList : inventory.detail) {
            assets.addAll(assetsList.asset);
        }

        Collections.sort(assets, new Comparator<Assets>() {
            @Override
            public int compare(Assets lhs, Assets rhs) {
                int flag = 0;
                try {
                    if (lhs.strasset250 != null) {
                        if (rhs.getStrasset250() == null) {
                            rhs.setStrasset250("");
                        }
                        flag = lhs.getStrasset250().compareTo(rhs.getStrasset250());
                        if (flag == 0 && lhs.getStrasset250().length() > 0 && rhs.strasset250.length() > 0) {
                            flag = Integer.parseInt(lhs.getStrasset250().substring(1)) - Integer.parseInt(rhs.strasset250.substring(1));
                        }
                        if (flag == 0) {
                            flag = lhs.getAsset700() - rhs.getAsset700();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return flag;

            }
        });
        initAssetsListView(assets);

//        for (int x=0;x<3;x++){
//            checkList("00018007");
//            checkList("00018001");
//            checkList(x+"");
//        }
    }


    @Override
    public void exit(View view) {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        rfidList.clear();
        rfidList = null;
        setResult(RESULT_OK);
        finish();
    }

    public void save(View view) {
//        checkList(123456+"");
//        checkList(1234567+"");
//        checkList(12345689+"");
//        checkList(123456333+"");
//        checkList(123426+"");
//        checkList(1234267+"");
//        checkList(12341689+"");
//        checkList(123416333+"");
        DialogUtil.showTwoBtnDialog(this, "完成后不能再次采集，是否继续？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showToast("保存成功");
                inventory.setStatus(2);
                rfidList.clear();
                rfidList = null;
                /**
                 * 这部分代码是模拟扫描RFID盘点
                 **/
//                 Assets newAssets = new Assets();
//                 newAssets.asset70 = inventory.detail.get(0).getAsset().get(1).getAsset70();
//                 List<Assets> allData = assetsAdapter.getData();
//                 if (allData.contains(newAssets)) {
//                 Assets a = allData.get(allData.indexOf(newAssets));
//                 if (a.getStatus() == 1) {
//                 a.status = 3;
//                 assetsDao.update(a);
//                 }
//                 }

                inventoryDao.update(inventory);

                setResult(RESULT_OK);
                finish();
            }
        }, null);
    }

    private void initAssetsListView(List<Assets> assetsList) {

        if (null == assetsAdapter) {
            assetsAdapter = new AssetsAdapter(this, assetsList);
            inventoryListLv.setAdapter(assetsAdapter);
        } else {
            assetsAdapter.setData(assetsList);
        }
        // 开始扫描RFID
        if (application.checkServiceAndDevice()) {
            int power = SpUtil.getInstance(this).getKeyIntValue(SpUtil.Key.KEY_MAX_POWER, 23);
            application.device.uhfPowerOn();
            application.device.setUhfPower(power * 10, 200, 300);
            new GetRFIDThread().start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        bGetEPC = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        application.device.uhfPowerOff();
        if (bGetEPC) {
            bGetEPC = false;
        }
    }


    private class GetRFIDThread extends Thread {

        @Override
        public void run() {
            bGetEPC = true;
            while (bGetEPC) {
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    FFLog.e(e, e.getMessage());
                }

                try {
                    int cnt = application.device.getSize();
                    FFLog.i("--->cnt = " + cnt);

                    for (int i = 0; i < cnt; i++) {
                        UHFTag uhfTag = application.device.getItem();

                        if (uhfTag == null) {
                            continue;
                        }

                        String epc = uhfTag.getEpc(true).replace(" ", "");
                        int length = epc.length();
                        String type;
                        while (length>4){
                            type = epc.substring(length-2,length);
                            try{
                                if (Integer.parseInt(type)<30 || Integer.parseInt(type)>39){
                                    final String rfid = epc.substring(epc.length() - 8, epc.length());
                                    FFLog.i("--->rfid:", rfid);
                                    if (!cacheRfid.contains(rfid)) {
                                        cacheRfid.add(rfid);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                checkList(rfid);
                                            }
                                        });

                                    }
                                    break;
                                }
                            }catch (Exception e){
                                FFLog.e(e, e.getMessage());
                                continue;
                            }
                            length = length-2;
                        }

                    }
                } catch (Exception e) {
                    FFLog.e(e, e.getMessage());
                }
            }
        }
    }

    private List<String> cacheRfid = new ArrayList<>();

    private void checkList(String rfid) {
        Assets newAssets = new Assets();
        newAssets.asset70 = rfid;

        List<Assets> allData = assetsAdapter.getData();
        if (allData.contains(newAssets)) {
            Assets a = allData.get(allData.indexOf(newAssets));
            if (a.getStatus() == 1) {
                a.status = 3;

                assetsDao.update(a);
            }
        } else {
            newAssets.status = 5;
            newAssets.setAssetsListId(inventory.detail.get(0).get_id());
            allData.add(newAssets);
            assetsDao.insert(newAssets);


            Message message=new Message();
            Bundle bundle=new Bundle();
            bundle.putString("RFID",rfid);
            bundle.putString("型号",newAssets.strasset150);
            bundle.putString("机柜",newAssets.strasset250);
            bundle.putString("U位",newAssets.asset700+"");
            message.setData(bundle);
            message.what=1;
            mHandler.sendMessage(message);


        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                assetsAdapter.notifyDataSetChanged();
            }
        });

    }

    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                Bundle bundle=msg.getData();
                String rfid=bundle.getString("RFID");
                String modelTv=bundle.getString("型号");
                String jiguiTv=bundle.getString("机柜");
                String uTv=bundle.getString("U位");
                if (SpUtil.getInstance(InventoryListActivity.this).getKeyStringValue("switch", "").equals("on")) {
                    if (rfidList.contains(rfid) == false) {
                        rfidList.add(rfid);

                        DialogUtil.showRFIDDialog(InventoryListActivity.this,
                                "型号:" + modelTv + "\n" + "机柜:" + jiguiTv + "\n" + "U位:" + uTv + "\n" + "RFID:" + rfid,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                    }
                }
            }
        }
    };

    private static class AssetsAdapter extends GeneralAdapter<Assets> {


        public AssetsAdapter(Context ctx, List<Assets> data) {
            super(ctx, R.layout.view_inventory_list_item, data);
        }

        @Override
        public void convert(ViewHolder holder, final Assets item, int position) {
            TextView numTv = holder.getView(R.id.tv_inventory_list_item_num);
            TextView modelTv = holder.getView(R.id.tv_inventory_list_item_model);
            TextView jiguiTv = holder.getView(R.id.tv_inventory_list_item_jigui);
            final EditText uTv = holder.getView(R.id.tv_inventory_list_item_u);
            TextView rfidTv = holder.getView(R.id.tv_inventory_list_item_rfid);
            CheckBox statusCb = holder.getView(R.id.cb_inventory_list_item_status);
            TextView statusTv = holder.getView(R.id.tv_inventory_list_item_status);

            numTv.setText(String.valueOf(position + 1));
            modelTv.setText(item.strasset150);
            jiguiTv.setText(item.strasset250);
            uTv.setText(item.asset700 + "");
            rfidTv.setText(item.asset70);

            if (item.status == 1) {
                statusCb.setChecked(false);
                statusTv.setText("未盘");
            } else if (item.status == 3) {
                statusCb.setChecked(true);
                statusTv.setText("已盘");
            } else if (item.status == 5) {
                statusCb.setChecked(true);
                statusTv.setText("盘盈");
            }


            uTv.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    item.asset700 = Integer.parseInt(uTv.getText().toString().trim());
                    DBUtil.getAssetsDao(getContext()).update(item);
                    return false;
                }
            });
        }
    }
}
